
#include <misc.h>
#include <stm32f10x.h>
#include <stm32f10x_rcc.h>
#include <stm32f10x_tim.h>

#include "timer.h"

int seconds,mins,hours;
int b_seconds,b_mins,b_hours;
int last_seconds;

// 使用Tim2定时一秒钟
void Init_Tim2(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    // 使能Tim2的时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    // 初始化时基单元
    TIM_TimeBaseStructure.TIM_Prescaler = 7200 - 1;             // 设置预分频值
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 设置计数器模式
    TIM_TimeBaseStructure.TIM_Period = 10000 - 1;               // 设置计数器自动重装值
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;     // 设置时钟
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); // 使能指定的TIM2中断

    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    // 使能定时器
    TIM_Cmd(TIM2, ENABLE);
}

/*
*开启定时器时钟
*定时器初始化结构体配置
*定时器中断开启
*定时器使能
72M
*/
void Init_Tim3(void)
{
    TIM_TimeBaseInitTypeDef TIM_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
    TIM_InitStruct.TIM_Prescaler = 7200 - 1; // 72M/7200 = 10000 （周期为T=1/10000）
    TIM_InitStruct.TIM_Period = 10000 - 1;   // 10000 / 10000 = 1 HZ  1/1HZ = 1S   （10000*T = 1S）
    TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_InitStruct.TIM_ClockDivision = 0;
    TIM_TimeBaseInit(TIM3, &TIM_InitStruct);
    TIM_ClearFlag(TIM3, TIM_FLAG_Update);
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
    //	TIM_Cmd(TIM3,ENABLE); //不使能，后续通过按键使能
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    NVIC_InitStruct.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 2;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
}

//定时器中断函数
void TIM3_IRQHandler(void)   //TIM3中断
{ 
	if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查指定的TIM中断发生与否:TIM 中断源 
	{
		seconds++;
		b_seconds--;
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update);  //清除TIMx的中断待处理位:TIM 中断源 
	}
}

